package com.neiquan.backstage.web.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.neiquan.backstage.common.util.Sessions;
import com.neiquan.backstage.pub.bsc.dao.po.PlatformAdminUser;

public class PlatformViewPermissionChecker {
	private static final String super_admin_user_account = "admin";
	private static final String page_login = "/platform_login.jsp";
	private static final String page_permission_denied = "/platform_permission_denied.jsp";
	private static final List<String> public_pages = new ArrayList<>();
	private static final List<String> authc_pages = new ArrayList<>();

	static {
		public_pages.add(page_login);
		authc_pages.add(page_permission_denied);
	}

	public static boolean canAccessPage(String page, HttpServletRequest httpReq) throws NotLoginedException {
		Object loginedUserObject = Sessions.getLoginedUser(httpReq.getSession());
		PlatformAdminUser platformAdminUser = loginedUserObject instanceof PlatformAdminUser ? (PlatformAdminUser) loginedUserObject : null;

		if (public_pages.contains(page)) {
			// 特殊页面，公共权限，无需登录
			return true;
		}

		if (platformAdminUser == null) {
			// 未登录
			throw new NotLoginedException();
		}

		if (authc_pages.contains(page)) {
			// 特殊页面，任何用户登录后即可访问
			return true;
		}

		if (isSuperAdminUser(platformAdminUser)) {
			// 超级管理员，拥有最高权限
			return true;
		}

		// TODO 加入权限验证
		return true;
	}

	public static void sendRedirectPageLogin(HttpServletRequest httpReq, HttpServletResponse httpResp) throws IOException {
		httpResp.sendRedirect(httpReq.getContextPath() + page_login);
	}

	public static void sendRedirectPagePermissionDenied(HttpServletRequest httpReq, HttpServletResponse httpResp) throws IOException {
		httpResp.sendRedirect(httpReq.getContextPath() + page_permission_denied);
	}

	private static boolean isSuperAdminUser(PlatformAdminUser platformAdminUser) {
		return super_admin_user_account.equals(platformAdminUser.getAccount());
	}
}
